<?php

namespace app\admin\controller\shop;

use AlibabaCloud\SDK\Iot\V20180120\Models\DeleteDestinationResponseBody;
use AlibabaCloud\SDK\Iot\V20180120\Models\InvokeDataAPIServiceRequest\param;
use app\admin\model\User;
use app\common\controller\Backend;
use fast\Http;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 店铺设备管理
 *
 * @icon fa fa-circle-o
 */
class Shopdevice extends Backend
{

    protected $noNeedRight = ['queryStatus'];
    protected $searchFields = 'device_sn,shop.name';

    /**
     * Shopdevice模型对象
     * @var \app\admin\model\Shopdevice
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shopdevice;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("deviceType", $this->model->getDeviceType());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['shop', 'room', 'table'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {


            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $device_type = $params['type'];
        $shop_id = $params['shop_id'];
        $devices = $params['device_sn'];
        $deviceList = array();

        //分割设备
        try {
            $deviceList = preg_split("/\r\n|\n|\r/", $devices);
        } catch (\Exception $e) {
            $this->error('分割失败,原因：' . $e->getMessage());
        }

        // 移除空字符串和null值
        $deviceList = array_filter($deviceList, function ($value) {
            return ($value !== null && $value !== '');
        });

        //查询店铺信息
        $shopModel = new \app\admin\model\Shop();
        $shopInfo = $shopModel->where('id', $shop_id)->find();

        //查询设备是否已经存在
        $shopDeviceModel = new \app\admin\model\Shopdevice();
        $deviceResult = $shopDeviceModel->where('device_sn', 'in', $deviceList)->select();
        if (!empty($deviceResult)) {
            $newDevice = array();
            foreach ($deviceResult as $v) {
                $newDevice[] = $v['device_sn'];
            }
            $isExit = implode(',', $newDevice);
            $this->error('设备【'.$isExit.'】已经存在');
        } else {
            $newInsert = array();
            foreach ($deviceList as $n){
                $db = array();
                $db['device_sn'] = $n;
                $db['shop_id'] = $shopInfo['id'];
                $db['user_id'] = $shopInfo['user_id'];
                $db['device_type'] = $device_type;
                $db['org_id'] = 27;
                $db['version'] = 3;
                $newInsert[] = $db;
            }
            $shopDeviceModel->insertAll($newInsert);
        }
        $this->success('添加成功');
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }

                $device_type = $params['device_type'];
                $device_sn = $params['device_sn'];
                $shop_id = $params['shop_id'];
                $room_id = $params['room_id'];
                $table_id = $params['table_id'];

                //查询店铺信息
                $shopModel = new \app\admin\model\Shop();
                $shopInfo = $shopModel->where('id', $shop_id)->find();
                if (!$shopInfo) {
                    $this->error('店铺不存在');
                }
                $user_id = $shopInfo['user_id'];

                //判断是棋牌还是台球
                switch ($device_type) {
                    case 'qp':
                        if ($room_id > 0) {
                            //先判断包厢是否已经被绑定,如果已绑定先解锁
                            $deviceRoom = $this->model->where('room_id', $room_id)->where('device_type', 'qp')->find();
                            if ($deviceRoom) {
                                $this->model->where('device_sn', $deviceRoom['device_sn'])->update(['shop_id' => -1, 'room_id' => -1, 'type' => '', 'bind_status' => -1]);
                            }

                            //更新设备绑定状态
                            $this->model->where('device_sn', $device_sn)->update(['user_id' => $user_id, 'shop_id' => $shop_id, 'room_id' => $room_id, 'type' => '', 'bind_status' => 1]);

                            //更新包厢状态
                            Db::name('shop_room')->where('id', $room_id)->update(['is_bind' => 1]);
                        } else {
                            //更新设备绑定状态
                            $this->model->where('device_sn', $device_sn)->update(['user_id' => $user_id, 'shop_id' => $shop_id, 'room_id' => -1, 'type' => '', 'bind_status' => -1]);
                        }
                        break;
                    case 'tq':

                        if ($table_id > 0) {
                            $deviceRoom = $this->model->where('room_id', $table_id)->where('device_type', 'tq')->find();
                            if ($deviceRoom) {
                                $this->model->where('device_sn', $deviceRoom['device_sn'])->update(['shop_id' => -1, 'room_id' => -1, 'type' => '', 'bind_status' => -1]);
                            }

                            //更新设备绑定状态
                            $this->model->where('device_sn', $device_sn)->update(['user_id' => $user_id, 'shop_id' => $shop_id, 'room_id' => $table_id, 'type' => '', 'bind_status' => 1]);

                        } else {
                            //更新设备绑定状态
                            $this->model->where('device_sn', $device_sn)->update(['user_id' => $user_id, 'shop_id' => $shop_id, 'room_id' => -1, 'type' => '', 'bind_status' => -1]);
                        }
                        break;
                    default:
                        $this->error('没有 ' . $device_type . ' 类型的设备');
                }

                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function queryStatus()
    {


        $device_sn = $this->request->param('device_sn');

        $req = array();
        $req['device_sn'] = $device_sn;
        $result = Http::post("https://qhy.51fxyf.com/api/shop/device/queryStatus", $req);

        $result = json_decode($result, true);
        if ($result['data'] == 'online') {
            $this->success("在线");

        } else {
            $this->success("离线");

        }
    }


}
